package fr.appliClient.client;

import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.ui.HasWidgets;

/**
 * Application general controller
 * 
 * @author renavarr
 * 
 */
public class AppController implements ValueChangeHandler<String> {

	// The rootpanel on which views are attached for display.
	private HasWidgets rootPanel;

	// The WidgetFactory.
	private WidgetFactory widgetFactory;

	public AppController(HasWidgets rootPanel, WidgetFactory widgetFactory) {

		this.rootPanel = rootPanel;
		this.widgetFactory = widgetFactory;

		bind();
	}

	/**
	 * call home page on root panel
	 */
	public void go() {

		this.widgetFactory.getMainPresenter().go(this.rootPanel);

		if (History.getToken().equals("")) {
			History.newItem("module");
		} else {
			History.fireCurrentHistoryState();
		}
	}

	@Override
	public void onValueChange(ValueChangeEvent<String> event) {

		HasWidgets widgetContainer = this.widgetFactory.getRootContainter();
		String historyToken = event.getValue();
		if (historyToken != null) {
			if (historyToken.equals("home")) {
				this.widgetFactory.getMainPresenter().go(this.rootPanel);
			} else {
				this.widgetFactory.getMainPresenter().go(this.rootPanel);
			}
		}

	}

	/**
	 * bind to history events.
	 */
	private void bind() {

		History.addValueChangeHandler(this);
	}

}
